<?php

namespace common\observer;

use common\model\UserModel;
use common\service\ChatService;
use support\SingletonTrait;
use teamones\Request;
use teamones\dbeventObserver\interfaces\SplObserver;
use teamones\dbeventObserver\interfaces\SplSubject;

class UpdateEntitySendMessageToChat implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     */
    function update(SplSubject $subject): void
    {
        $entity = $subject->getSubjectData();
        $updateEntityData = $subject->getSplUpdateData();
        $needModuleCode = ['design', 'storyboard'];
        $entityModuleCode = module_by_id($entity['module_id'])['code'];
        if (!in_array($entityModuleCode, $needModuleCode)) {
            return;
        }
        $allowSendMessage = false;
        $syncChatName = '';
        // 限制允许触发发送更新实体消息的字段
        if ($entityModuleCode == 'storyboard') {
            $allowStoryboardUpdateFields = ['initial_episode_code', 'showings_number', 'name', 'storyboard_production_method', 'storyboard_cloth_solution', 'storyboard_fx', 'storyboard_perform_form', 'description', 'storyboard_perform_species', 'storyboard_perform_numbers', 'duration', 'storyboard_type'];
            foreach ($allowStoryboardUpdateFields as $item) {
                if (array_key_exists($item, $updateEntityData)) {
                    $allowSendMessage = true;
                }
            }
        } else {
            $allowDesignUpdateFields = ['initial_episode_code', 'showings_number', 'design_perform_species', 'design_category', 'design_perform_species', 'design_grade', 'name'];
            foreach ($allowDesignUpdateFields as $item) {
                if (array_key_exists($item, $updateEntityData)) {
                    // 同步概念名到群名
                    if ($item == 'name') {
                        $syncChatName = $updateEntityData[$item];
                    }
                    $allowSendMessage = true;
                }
            }
        }
        if (!$allowSendMessage) {
            return;
        }
        $chatService = new ChatService();
        try {
            $chat = $chatService->createEntityChat($entity);
            if ($syncChatName) {
                $requestData = [
                    "data" => [
                        'id' => $chat['id'],
                        'name' => $syncChatName
                    ]
                ];
                teamones_request('teamones-im', 'chat/update', $requestData);
            }
            $message['type'] = 'update_entity_info_message';
            $message = $chatService->getEntityTaskMessageTemplate($message, \request()->getUserId(), $entity);
            $chatService->pushEntityTaskMessage($message, $chat);
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
